# -*- coding: utf-8 -*-
'''
Created on Dec 20, 2010

@author: behrooz
'''

from amscms import settings
from amscms.user_settings.models import UserSettings
from django.contrib.sites.models import Site
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.template.context import Context
from django.template.loader import get_template
from django.utils.translation import ugettext as _


def render_email_templates(template_name_text, template_name_html, context,
                           template_text=None, template_html=None):
    if not template_text: 
        template_text = get_template(template_name_text)
    if not template_html:    
        template_html = get_template(template_name_html)
    text_message = template_text.render(Context(context))
    html_message = template_html.render(Context(context))
    return  text_message, html_message

def send_email(to, context={}, fromaddr=settings.DEFAULT_FROM_EMAIL, \
                    template_name_text='base_email.txt', template_name_html='base_email.html',
                    domain_override=None, use_https=False):
    context = add_common_variable_to_context(context, domain_override, use_https)
    conn = mail.get_connection()
    conn.open()
    text_message, html_message = render_email_templates(template_name_text, template_name_html, context)
    email = EmailMultiAlternatives(context['subject'], text_message, fromaddr, [to], connection=conn)
    email.attach_alternative(html_message, "text/html")
    conn.send_messages([email])
    conn.close()

def send_emails(recipients, context={}, fromaddr=settings.DEFAULT_FROM_EMAIL, \
                    template_name_text='base_email.txt', template_name_html='base_email.html',
                    domain_override=None, use_https=False):
    context = add_common_variable_to_context(context, domain_override, use_https)
    text_message, html_message = render_email_templates(template_name_text, template_name_html, context)
    emails = []
    for r in recipients:
        email = EmailMultiAlternatives(context['subject'], text_message, fromaddr, [r])
        email.attach_alternative(html_message, 'text/html')
        emails.append(email)
    conn = mail.get_connection()
    conn.send_messages(emails)
    try: 
        conn.close()
    except:
        pass

def send_emails_parallel_to_messages(message_list, context={},
                                     domain_override=None, use_https=False):
    context = add_common_variable_to_context(context, domain_override, use_https)
    connection = mail.get_connection()
    connection.open()
    email_list = []

    t_text = get_template("private_messages/compose_email.txt")
    t_html = get_template("private_messages/compose_email.html")
    
    current_site = Site.objects.get_current()
    site_name = current_site.name
    
    for msg in message_list:
        # check the user notification settings
        recipient_user_settings, created = UserSettings.objects.get_or_create(user=msg.recipient)
        if created:
            recipient_user_settings.message_notify = True
            recipient_user_settings.save()
        if recipient_user_settings.message_notify:
            context['message'] = msg 
            context['msg_absolute_url'] = msg.get_absolute_url()
            body_text, body_html = render_email_templates("", "", context, t_text, t_html)
            if not msg.sender:
                subject_text = msg.subject
            else:
                subject_text = _(u"%(sender)s sent you a message on %(site_name)s.")% {'sender': msg.sender.first_name + ' ' + msg.sender.last_name,'site_name': site_name,} 
            email = mail.EmailMultiAlternatives(
                subject=subject_text,
                body=body_text,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[msg.recipient.email, ],
            )
            email.attach_alternative(body_html, "text/html")
            email_list.append(email) 
                
    connection.send_messages(email_list)
    connection.close()

def add_common_variable_to_context(context, domain_override=None, use_https=False):
    if not domain_override:
        current_site = Site.objects.get_current()
        site_name = current_site.name
        domain = current_site.domain
    else:
        site_name = domain = domain_override
    context['site_name'] = site_name
    context['domain'] = domain
    context['protocol'] = use_https and 'https' or 'http'
    return context
